package bgu.gaoxu.diary.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;

import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.toast.XToast;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;

import bgu.gaoxu.diary.MainActivity;
import bgu.gaoxu.diary.R;
import bgu.gaoxu.diary.adapter.MyselfAdapter;
import bgu.gaoxu.diary.entity.MyselfList;
import bgu.gaoxu.diary.entity.UserIF;
import bgu.gaoxu.diary.expression.ExpressionActivity;
import bgu.gaoxu.diary.finalvalue.Common;
import bgu.gaoxu.diary.tts.TtsDemo;
import bgu.gaoxu.diary.utils.GsonUtils;
import bgu.gaoxu.diary.utils.LoginState;
import okhttp3.Call;

public class AccountSoft extends AppCompatActivity {
    SharedPreferences settingprefre;
    private ListView listView;
    private MyselfAdapter myselfAdapter;
    UserIF u = new UserIF();
    LoginState loginState = new LoginState();
    private ArrayList<MyselfList> myselfLists = new ArrayList<MyselfList>();
    private String[] title = new String[]{"锁忆号", "昵称", "锁忆密码", "指纹登录"};
    private String[] dependency = new String[4];
    private int[] url_pic = new int[]{R.drawable.list_myfriend, R.drawable.about, R.drawable.accountlock, R.drawable.finger};
    private SharedPreferences mySharedPreferences ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_soft);
        init_actionBar();
        mySharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        listView = findViewById(R.id.accountsoftlist);
        myselfLists.clear();
        init_Data();
        myselfAdapter = new MyselfAdapter(this, myselfLists, listView);
        listView.setAdapter(myselfAdapter);
        init_onclick();
    }

    private void init_onclick() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                XToast.success(getActivity(), title[i]).show();
                Intent it = new Intent();
                if (u.getUser_id() != -1) {
                    switch (i) {
                        case 0:
                            showInputDialog(0);
                            break;
                        case 1:
                            showInputDialog(1);
                            break;
                        case 2:
                            showInputDialog(2);
                            break;
                        case 3:
                            popSetting();
                            break;
                    }
                } else {
                    it.setClass(AccountSoft.this, LoginActivity.class);
                    startActivity(it);
                }

            }
        });
    }

    /**
     * 带输入框的对话框
     */
    private void showInputDialog(int postion) {

        new MaterialDialog.Builder(this)
                .iconRes(R.drawable.about)
                .title("请输入密码")
                .content("验证密码后即可修改")
                .inputType(
                        InputType.TYPE_CLASS_TEXT
                                | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                                | InputType.TYPE_TEXT_FLAG_CAP_WORDS)
                .input(getString(R.string.hint_please_input_password),
                        "",
                        false,
                        ((dialog, input) -> Log.e("修改",postion+"")))
                .inputRange(6, 20)
                .positiveText("验证")
                .negativeText("取消")
                .onPositive((dialog, which) -> changeinfo(dialog.getInputEditText().getText().toString(), postion))
                .cancelable(false)
                .show();

    }

    private void upUserInfo(String param,int postion) {
        Log.e("提交修改：", title[postion]);
        String key = "";
        switch (postion){
            case 0:
                key = "user_name";
                break;
            case 1:
                key = "user_nickname";
                break;
            case 2:
                key = "user_psd";
                break;
        }
        OkHttpUtils.post().url(Common.SERVERURL+"/mydiary/UpUserInFo.do").addParams(key,param).addParams("param",key)
                .addParams("user_id",u.getUser_id()+"").build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("Exception",e+"");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try{
                            UserIF user = GsonUtils.fromJson(response, UserIF.class);
                            SharedPreferences.Editor editor = mySharedPreferences.edit();
                            editor.putString("user_name", user.getUser_name());
                            editor.putInt("user_id", user.getUser_id());
                            editor.putInt("user_diarynum", user.getDiarynum());
                            editor.putInt("user_friendnum", user.getFriendnum());
                            editor.putString("user_photo", user.getUser_photo());
                            editor.putString("user_nickname", user.getNickname());
                            editor.putString("user_psd", user.getUser_psd());
                            editor.apply();
                            reflist();
                        }catch (Exception e){

                        }
                    }
                });

    }

    private void reflist() {
        myselfLists.clear();
        init_Data();
        myselfAdapter = new MyselfAdapter(this, myselfLists, listView);
        listView.setAdapter(myselfAdapter);
    }

    private void changeinfo(String password, int postion) {
        if (password.equals(u.getUser_psd())) {
            String prefill = "";
            switch (postion){
                case 0:
                    prefill = u.getUser_name();
                    break;
                case 1:
                    prefill = u.getNickname();
                    break;
                case 2:
                    prefill = u.getUser_psd();
                    break;
            }
            XToast.success(this,"密码验证成功").show();
            new MaterialDialog.Builder(this)
                    .iconRes(url_pic[postion])
                    .title("修改" + title[postion])
                    .content("请输入符合要求的"+title[postion]+"类型")
                    .inputType(
                            InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS)
                    .input("请输入新的" + title[postion],
                            prefill,
                            false,
                            ((dialog, input) -> Log.e("修改",postion+"")))
                    .inputRange(6, 20)
                    .positiveText("修改")
                    .negativeText("取消")
                    .onPositive((dialog, which) -> upUserInfo(dialog.getInputEditText().getText().toString(),postion))
                    .cancelable(false)
                    .show();
        } else {
            XToast.error(this, "密码错误").show();
        }
    }


    private void init_Data() {
        LoginState loginState = new LoginState();
        u = loginState.getUserInfo(this);
        dependency[0] = u.getUser_name();
        dependency[1] = u.getNickname();
        dependency[2] = "*********";
        dependency[3] = "去开启";
        int count = 0;
        for (String tit : title) {
            MyselfList myselfList = new MyselfList();
            myselfList.setDependency(dependency[count]);
            myselfList.setListtext(tit);
            myselfList.setListpic(url_pic[count]);
            myselfLists.add(myselfList);
            count++;
        }
    }

    private void popSetting() {
        settingprefre = getSharedPreferences("setting", 0);
        String res = settingprefre.getString("fingerstate", "false");
        if (res.equals("false")) {
            new MaterialDialog.Builder(this)
                    .title("指纹识别")
                    .content("当前指纹识别未开启，是否开启")
                    .positiveText("开启").onPositive((dialog, which) -> setfinger(0))
                    .negativeText("取消")
                    .show();
        } else {
            new MaterialDialog.Builder(this)
                    .title("指纹识别")
                    .content("当前指纹识别已开启，是否关闭")
                    .positiveText("关闭").onPositive((dialog, which) -> setfinger(1))
                    .negativeText("取消")
                    .show();
        }

    }

    public void setfinger(int i) {
        settingprefre = getSharedPreferences("setting", 0);
        SharedPreferences.Editor ed = settingprefre.edit();
        switch (i) {
            case 0:
                ed.putString("fingerstate", "true");
                break;
            case 1:
                ed.putString("fingerstate", "false");
                break;
        }
        ed.apply();
    }

    public void init_actionBar() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.bottom_bgcolor));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    }

}